<!--应急计划 plan-->
<template>
  <Layout>
    <Form ref="form1" :model="dataToQuery" :label-width="120">
      <Row v-show="!switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="企业名称：" prop="order">
            <!--            <cascaderDom class="query-form-el" ref="queryOrgCascader"-->
            <!--                         @setOrgInfo="setQueryCompanyName" @setOrgname="setQueryOrgName"-->
            <!--                         :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"-->
            <!--                         :orgTree="true"></cascaderDom>-->
            <company-select v-model="dataToQuery.companyName" class="query-form-el"></company-select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="二级集团：" prop="order">
            <two-level-org class="query-form-el" v-model="dataToQuery.twoLevelOrgId"></two-level-org>
          </FormItem>
        </Col>
        <Col span="8">
<!--          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>-->
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="企业名称：" prop="belongOrgId">
            <cascader-dom class="query-form-el" ref='queryOrgCascader1' @setOrgInfo='setQueryCompanyName'
                          :orgTree="true"
                          :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label='处罚类别：' prop='punishmentType'>
            <Select class='query-form-el' placeholder="请选择处罚类别" type='text' v-model='dataToQuery.punishmentTypeArrays'
                    multiple>
              <Option v-for="item in dictMap['ENEVT-000002']" :value="item.codingCodeId" :key="item.codingCodeId">
                {{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="事件发生时间：" prop="content">
            <DatePicker class="query-form-el" v-model="dataToQuery.dateRange" format="yyyy-MM-dd" type="daterange"
                        placement="bottom-end" placeholder="请选择查询时间段"
                        @on-change="(data)=> {this.onSelectFieldQueryDateRange(data, 'eventDate')}"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="填表时间：" prop="content">
            <DatePicker class="query-form-el" v-model="dataToQuery.dateRange" format="yyyy-MM-dd" type="daterange"
                        placement="bottom-end" placeholder="请选择查询时间段"
                        @on-change="onSelectQueryDateRange"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8" offset="8">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="exportFormSubmit">导出</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows' @on-sort-change="querySort"
           :loading='pageStatus.loading'
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>
    <Modal title="应急计划" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow" :width=800
         class-name='limit-height-dialog'>
      <Row>
        <Col span="24">
          <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false"
                :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?190:null"
                :label-position="mode === 'view'?'right':'top'">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
              <FormItem label='所属单位：' prop='companyName'>
                <div v-if="mode === 'view'">{{ dataToView.companyName }}</div>
                <cascader-dom v-else ref='orgCascader'
                              @setOrgInfo='(data)=>{cascaderDomIdChangeHandle(data,"companyId");}'
                              @setOrgname='(data)=>{cascaderDomNameChangeHandle(data,"companyName");}'
                              :orgTree="true" :currentOrgId="dataToView.eventOrgId"
                              :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}">
                </cascader-dom>
              </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label='二级集团：'>
                  <div v-if="mode === 'view'">{{ dataToView.twoLevelOrgName }}</div>
                  <Input v-else class='' readonly  type='text' v-model='dataToView.twoLevelOrgName'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='应急计划名称：' prop='planName'>
                  <div v-if="mode === 'view'">{{ dataToView.planName }}</div>
                  <Input v-else class='' placeholder="请填写应急计划名称" type='text' v-model='dataToView.planName'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='应急预案：' prop='measureId'>
                  <div v-if="mode === 'view'">{{ dataToView.measureName }}</div>
                  <Input v-else class='' readonly placeholder="请填写应急计划名称" type='text' v-model='dataToView.measureName'  @on-focus="openSelect"></Input>
                </FormItem>

              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label='填报人：' prop='createUserName'>
                  <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                  <Input v-else class=''placeholder="请填写填报人" type='text' v-model='dataToView.createUserName'></Input>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label='填报人电话：' prop='phone'>
                  <div v-if="mode === 'view'">{{ dataToView.phone }}</div>
                  <Input v-else class=''placeholder="请填写填报人电话" type='text' v-model='dataToView.phone'></Input>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">

              <Col span="23">
                <FormItem label='起止时间：' prop='planDate'>
                  <div v-if="mode === 'view'">{{formatePlanDate(dataToView.startDate,dataToView.endDate)}}</div>
                  <DatePicker v-else class="w" type="daterange"  placeholder="请选择起止时间" v-model='dataToView.planDate' ></DatePicker>
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem v-if="mode === 'view'" label="应急计划：">
                  <div v-show="uploadList.length>0" v-for="(item,index) in uploadList" :key='item'>
                    <a @click="downloadFile(dataToView.id,item,index)"><span
                        style="color: #3399ff;margin-left: 5px">{{ item.fileName }}</span></a>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
                <FormItem v-else label="应急计划：" prop="uploadList">
                  <div>
                    <Upload ref="upload"
                            :before-upload="beforeUpload"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 10px">
                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                      </div>
                    </Upload>
                  </div>
                  <div v-show="uploadList.length>0" v-for="(item,index) in uploadList" :key='item'>
                    <a @click="downloadFile(dataToView.id,item,index)">{{ item.fileName }}</a>
                    <Button type="text" icon="md-trash" @click="remove1(item.id)"
                            style="margin-left: 5px;margin-bottom: 3px"/>
                    <Progress v-show="uploadListVisible[index]" :percent="uploadListPercent[index]"></Progress>
                  </div>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-save' @click="submit('dialogForm')">确定</Button>
        <Button v-if="mode != 'view'" type="primary" class='ivu-btn-cancel' @click="handleCancel">取消</Button>
        <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
      </div>
    </Modal>
    <Modal title="应急预案选择" :transfer=false footer-hide v-model="measureModel" :width=900>
      <measureSelect ref="selMission" @selectMission="selectMission">
      </measureSelect>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {formatDate} from '@/tools/index'
import measureSelect from "../measure/measureSelect.vue"
import pageCommonFunction from '@/components/pageCommonFunction.js'

var cascaderDom = () => import('@/components/cascader-dom.vue');

export default {
  components: {
    cascaderDom, measureSelect
  },
  data() {
    return {
      ...this.createCommonDataField(),
      columns1: [
        {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {
          title: "应急演练",
          width: 130,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            let color = 'green';
            if (params.row.fillIn != '1'){
              color = 'red';
            }
            return h('span',{
              style: {
                color: color
              }
            }, params.row.fillIn == '1'?'已填报':'未填报');
          }
        },
        {key: 'planName', title: '应急计划名称', align: 'center', width: 200},
        {key: 'measureName', title: '应急预案名称', align: 'center', width: 200},
        {key: 'companyName', title: '所属单位', align: 'center', minWidth: 140},
        {key: 'twoLevelOrgName', title: '所属二级集团', align: 'center', width: 160},
        {
          key: 'startDate', title: '起止时间', align: 'center', minWidth: 200, render: (h, params) => {
            return h('span',this.formatePlanDate(params.row.startDate,params.row.endDate));
          }, sortable: 'custom',
        },
        {key: 'createUserName', title: '填报人', align: 'center', minWidth: 100},
        {key: 'phone', title: '填报人电话', align: 'center', minWidth: 100},
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 160,
          align: 'center',
          render: (h, params) => {
              const enable =  this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                      ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined
            if (enable) {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      // this.viewData(params);
                      this.dataToView = JSON.parse(JSON.stringify(params.row));
                      this.getFiles()
                      this.mode = 'view'
                      this.dialogShow = true
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  disabled: true,
                  style: {fontSize: '14px'},
                  on: {
                    click: () => {
                      this.dataToView = JSON.parse(JSON.stringify(params.row));

                      if (this.dataToView.startDate && this.dataToView.endDate){
                        this.dataToView.planDate = [this.dataToView.startDate,this.dataToView.endDate]
                      }
                      this.getFiles()
                      this.dialogShow = true
                      this.mode = 'edit'
                      this.add = false
                    }
                  }
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',
                      color: params.row.fillIn != '1'&& enable ?'red':'#c5c8ce',
                      pointerEvents:params.row.fillIn != '1'&& enable ?'':'none',},
                  on: {
                    click: () => {
                      this.deleteData(params);
                    }
                  }
                }, '删除')
              ]);
            } else {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.dataToView = JSON.parse(JSON.stringify(params.row));
                      this.getFiles()
                      this.mode = 'view'
                      this.dialogShow = true
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }
          }
        }
      ],
      ruleCustom: {
        planName: [ { required: true, message: '请填写应急计划名称', trigger: 'change',}],
        companyName: [ { required: true, message: '请填写所属单位', trigger: 'change',}],
        planDate:  [{
          validator: (rule, value, callback) => {
            if (this.dataToView.planDate[0]&&this.dataToView.planDate[1]) {
              callback();

            } else {
              callback(' ')
            }
          },
          required: true,
          trigger: 'change'
        }],
        createUserName: [ { required: true, message: '请填写填报人', trigger: 'change',}],
        measureId: [{
          validator: (rule, value, callback) => {
            if (!this.dataToView.measureId) {
              callback(' ');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        phone: [{
          validator: (rule, value, callback) => {
            if (!(/^1[3456789]\d{9}$/.test(this.dataToView.phone))) {
              callback(' ');
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'blur'
        }],
        uploadList: [{
          validator: (rule, value, callback) => {
            if (this.uploadList.length < 1) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          message: '请上传附件',
          trigger: 'change'
        }],
      },
      tableHeight: 10,
      uploadListVisible: [],
      uploadListPercent: [],
      dictMap: {},
      dataToView: {},
      uploadList: [],
      type: this.$route.query.id,
      measureModel: false,
      // api
      queryUrl: Api.queryEmergencyPlan,
      deleteUrl: Api.deleteEmergencyPlan,
      updateUrl: Api.updateEmergencyPlan,
      saveUrl: Api.saveEmergencyPlan,

      exportUrl: Api.downloadEmergencyPlan,
    }
  },
  async mounted() {
    this.setTableHeight();
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    deleteData(params) {
      this.deleteDateAjax(params);
    },
    formatePlanDate(startDate,endDate){
      if (startDate && endDate){
        return formatDate(new Date(startDate),'yyyy-MM-dd') +"~"+ formatDate(new Date(endDate),'yyyy-MM-dd')
      }else{
        return "--";
      }

    },
    openSelect() {
      this.measureModel = true
    },
    query() {
      if (this.dataToQuery.punishmentTypeArrays) {
        this.dataToQuery.punishmentTypes = this.arrayToInFormat(this.dataToQuery.punishmentTypeArrays)
      }
      this.dataToQuery.type = this.type;
      this.queryAjax();
    },
    submit(name) {

      if (this.dataToView.planDate.length != 0){
        this.dataToView.startDate = this.dataToView.planDate[0];
        this.dataToView.endDate = this.dataToView.planDate[1];
      }
      if (this.uploadList.length < 1) {
        this.$Message.error('请上传附件!');
      }else{
        this.dataToView.emeType = this.type;
        this.submitAjax(name);
      }

    },

    addInfo() {
      this.dataToView = {};
      this.uploadList = [];
      this.dataToView = (this.createEmptyDataToAdd instanceof Function) ? this.createEmptyDataToAdd() : {};
      this.dataToView.companyId = this.currentUser.companyId;
      this.dataToView.companyName = this.currentUser.companyName;
      this.dataToView.belongOrgId = this.currentUser.twoLevelOrgId;
      this.dataToView.belongOrgName = this.currentUser.twoLevelOrgName;
      this.dataToView.registrant = this.currentUser.userName;
      this.dataToView.registrantPhone = this.currentUser.mobileNumber;
      this.dataToView.registTime = new Date();
      this.dataToView.id = this.get_uuid();
      this.mode = 'add'
      this.dialogShow = true;
      setTimeout(() => {
        this.dialogVisibleChangeHandele(this.dialogShow)
      }, 100)
    },
    selectMission(row) {

      this.measureModel = false;
      this.dataToView.measureName = row.emName;
      this.dataToView.measureId = row.emId;


    },
    downloadFile(guideId, file, index) {
      let url = this.fileUrl + '/file/' + file.id;
      var _this = this;
      this.uploadListVisible[index] = true;
      this.$http.get(url, {
        responseType: 'blob',      //告诉服务器我们需要的响应格式
        progress: function (e) {
          _this.$set(_this.uploadListPercent, index, 100 * (e.loaded / e.total));
        }
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },
    remove1(id) {
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles()
      })
    },
    beforeUpload(file) {
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.dataToView.id + '/files/guideFile'
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles();
        }
      });
      return false
    },
    getFiles() {
      let url = this.fileUrl + '/' + this.dataToView.id + '/files/guideFile'
      this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data
          let index = 0;
          this.uploadList.forEach(item=>{
            this.uploadListPercent[index]=0;
            this.uploadListVisible[index] = false;
            index++;
          })
        }
      })
    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      return a;
    },
    handleCancel() {
      this.dataToView = {};
      this.dialogShow = false;
      this.query();
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    createEmptyDataToAdd() {
      return {
        id:this.get_uuid(),
        createUserName:this.currentUser.userName,
        phone:this.currentUser.mobileNumber,
        twoLevelOrgId:this.currentUser.twoLevelOrgId,
        twoLevelOrgName:this.currentUser.twoLevelOrgName,
        planDate:[],
      }
    },
    querySort({column, key, order}){
      this.dataToQuery.key = key;
      this.dataToQuery.order = order;
      this.query();
    }
  },
  watch: {},
}
</script>

<style lang='css' scoped>
@import '../../../../index.css';
</style>
